# -*- coding: utf-8 -*-
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "陪伴终身意外伤害保险"

    def genProductInfo(self):
        plan = {
            "planA": {
                "days": ["zs"],
                "year": [str(i) for i in range(18, 61)],
                "people_count": ["1"],
                "money": ["100000"],
                "payType": ["年交", "月交"],
                "interval": ["10"]
            },
            "planB": {
                "days": ["zs"],
                "year": [str(i) for i in range(18, 61)],
                "people_count": ["1"],
                "money": ["100000"],
                "payType": ["年交", "月交"],
                "interval": ["20"]

            }
        }
        for k in plan:
            for v in product( plan[k]["days"],plan[k]["year"], plan[k]["people_count"], plan[k]["money"],
                             plan[k]["payType"], plan[k]["interval"]):
                data = Helper.formatProductInfo( plan[k],v )
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data)  )
    #执行爬虫
    def requestJson(self,dt=None,mysql=None):
        params = '''
        appName: 
        appSex: M
        appidType: A
        appidNo: 
        appBirthday: 1993-02-02
        appPhone: 
        appPro: 110000
        appCity: 110100
        appAddress: 
        appEmail: 
        name: 
        sex: M
        idType: A
        idNo: 
        birthday: 1993-02-02
        phone: 
        pro: 110000
        city: 110100
        address: 
        email: 
        source: CUS000000046
        planCode: P000000864
        planAmnt: 100000
        polTerm: 106
        poltermType: A
        payPeriod: 20
        payIntv: 12
        relation: 0
        validate: 
        '''
        data = Helper.perfectJson( params )
        data["appBirthday"] = "{0}-01-01".format(str(2020 - int(dt["year"])))
        data["birthday"] = "{0}-01-01".format(str(2020 - int(dt["year"])))
        data["payIntv"] = "12" if dt["payType"] == "年交" else "1"
        data["payPeriod"] = dt["interval"]
        data["planCode"] = "P000000860" if dt["interval"] == "10" else "P000000864"

        payload = urlencode(data).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "msg" in r.text:
            price = Helper.decimalParse( r.json()["msg"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data)
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*产品价格数据更新失败:%d*/"%dt["id"])
